package netcom;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import netcom.messages.BConMessage;
import netcom.messages.Message;
import utilities.Constants;
import utilities.SerializableClassUtility;


public class ServiceLIstenerThread implements Runnable {

	private static boolean run = true;

	private DatagramSocket serverSocket;
	@Override
	public void run() {
		 try {
				serverSocket = new DatagramSocket(Integer.valueOf(Constants.BQ_PORT));
				serverSocket.setBroadcast(true);
				byte[] buffer = new byte[65536];
		        DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
		        
		        while(run){
		        	serverSocket.receive(incoming);
		    
		        	byte[] data = incoming.getData();
		            Message m = (Message)SerializableClassUtility.getMessaFromBytes(data);
		        	
		            if(m instanceof BConMessage){
		            	System.out.println("Bcon from: "+incoming.getAddress().toString()+" Received");
		            	NetManager.getInstance().serviceBconReaceaved(incoming.getAddress().toString(), (BConMessage)m);
		            }
		            
		        }
		        
			} catch (Exception e) {
				  run = false;
			}
	}

}
